package com.hyperfix.washer.websocket;

import com.hyperfix.washer.common.StatusRegistrar;
import com.hyperfix.washer.config.ServerEncoder;
import com.hyperfix.washer.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author JiangChunYu
 * 2024/4/30
 */
@Slf4j
@Component
@ServerEndpoint(
        value = "/status/{userId}",
        encoders = {ServerEncoder.class},
        subprotocols = {"protocol"},
        configurator = WebSocketConfig.class
)
public class StatusWebSocket {
    private static StatusRegistrar statusRegistrar;

    @Resource
    public void setStatusRegistrar(StatusRegistrar statusRegistrar) {
        StatusWebSocket.statusRegistrar = statusRegistrar;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        statusRegistrar.addSession(userId, session);
    }

    @OnClose
    public void onClose(@PathParam("userId") Integer userId) {
        statusRegistrar.removeSession(userId);
    }
}
